﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using System.Web;
using TBlog.Web.Models;

namespace TBlog.Web.Data
{
    public class EFContext : DbContext, IDbContext
    {
        public EFContext()
            : base("name=DefaultConnectionString")
        {
            // Database.SetInitializer<EFContext>(null);
           Database.SetInitializer(new DropCreateDatabaseAlways<EFContext>());
        }

        public EFContext(string name = "DefaultConnectionString")
            : base(name)
        {
           Database.SetInitializer<EFContext>(null);
            // Database.SetInitializer(new DropCreateDatabaseAlways<EFContext>());
        }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {


            var types = Assembly.GetExecutingAssembly().GetTypes()
                .Where(type => !string.IsNullOrWhiteSpace(type.Namespace))
                .Where(type => type.BaseType != null && type.BaseType.IsGenericType && type.BaseType.GetGenericTypeDefinition() == typeof(BaseEntityTypeConfiguration<>));

            foreach (var item in types)
            {
                dynamic config = Activator.CreateInstance(item);
                modelBuilder.Configurations.Add(config);
            }
            base.OnModelCreating(modelBuilder);
        }
    

        public IDbSet<T> DbSet<T>() where T : Models.BaseEntity
        {
            return base.Set<T>();
        }
        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);
        }
    }
}